<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入标题"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBill">
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.purchaseBill"
                    placeholder="请输入单据编号"
                    disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep
                    placeholder="请选择申请人"
                    v-model="model.proposer"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicant">
                  <j-select-depart placeholder="请选择申请部门" :disabled="formDisabled" v-model="model.applicant" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    placeholder="请选择申请时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="employeeId">
                  <select-user-by-dep
                    :tdlx="3"
                    placeholder="请选择申请人"
                    :disabled="formDisabled"
                    @back="backUserInfo"
                    v-model="model.employeeId"/>
                </a-form-model-item>
              </a-col> -->
              <!--              <a-col :span="8">-->
              <!--                <a-form-model-item label="预计归还日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dateReturn">-->
              <!--                  <j-date-->
              <!--                    :show-time="true"-->
              <!--                    date-format="YYYY-MM-DD HH:mm"-->
              <!--                    :disabled="formDisabled"-->
              <!--                    placeholder="请选择预计归还日期"-->
              <!--                    v-model="model.dateReturn"-->
              <!--                    style="width: 100%" />-->
              <!--                </a-form-model-item>-->
              <!--              </a-col>-->
              <!--              <a-col :span="8">-->
              <!--                <a-form-model-item label="偿还方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payBack">-->
              <!--                  <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.payBack" dictCode="repay_type" placeholder="请选择偿还方式" />-->
              <!--                </a-form-model-item>-->
              <!--              </a-col>-->
              <a-col :span="24">
                <a-form-model-item label="物品用途" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseUse">
                  <a-textarea
                    :disabled="formDisabled"
                    :max-length="500"
                    v-model="model.purchaseUse"
                    rows="2"
                    placeholder="请输入物品用途"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea
                    :disabled="formDisabled"
                    :max-length="500"
                    v-model="model.remark"
                    rows="4"
                    placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="调出信息">
            <a-row :gutter="48" style="padding: 48px 16px">
              <!-- <a-col :span="8">
                <a-form-model-item label="调出单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="exportApplicant">
                  <j-select-company placeholder="请选择调出单位" :disabled="formDisabled" v-model="model.exportApplicant" @change="handleChangeExportApplicant"/>
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="调出团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="exportTeamId">
                  <select-team-input-can-back
                    placeholder="请选择调出团队"
                    :disabled="formDisabled"
                    v-model="model.exportTeamId"
                    :tdlx="3"
                    @back="handleChangeExportTeamId"
                    :purchaseCannibalizeDetailList="purchaseCannibalizeDetailList"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调出日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="exportTime">
                  <a-date-picker
                    style="width: 100%"
                    :disabled="formDisabled"
                    placeholder="请选择调出日期"
                    @change="handleDateExportChange"
                    v-model="model.exportTime"
                    :showTime="true"
                    format="YYYY-MM-DD HH:mm"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调出仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="exportWarehouse">
                  <a-select
                    v-model="model.exportWarehouse"
                    :disabled="formDisabled"
                    placeholder="请选择调出仓库"
                    :showSearch="true"
                    :allowClear="true"
                    :filterOption="filterOption"
                    :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
                    @change="handleExportWarehouseChange"
                  >
                    <a-select-option v-for="item in exportWarehouseList" :key="item.id" :value="item.id">
                      {{ item.categoryName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="物资明细">
            <ErpPurchaseCannibalizeDetailList
              ref="cannibalizeDetailList"
              :exportTeamId="model.exportTeamId"
              :exportTeamName="model.exportTeamId_dictText"
              :exportWarehouse="model.exportWarehouse"
              :storehouseName="model.exportWarehouse_dictText"
              @change="getList"
              :disabled="formDisabled"></ErpPurchaseCannibalizeDetailList>
          </a-collapse-panel>
          <a-collapse-panel key="4" header="调入信息">
            <a-row :gutter="48" style="padding: 48px 16px">
              <!-- <a-col :span="8">
                <a-form-model-item label="调入单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="foldApplicant">
                  <j-select-company placeholder="请选择调入单位" :disabled="formDisabled" v-model="model.foldApplicant" @change="handleChangeFoldApplicant"/>
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="调入团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="foldTeamId">
                  <select-team-input
                    placeholder="请选择调入团队"
                    :disabled="formDisabled"
                    v-model="model.foldTeamId"
                    :tdlx="3"
                    @back="handleChangeFoldTeamId" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调入日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="foldTime">
                  <a-date-picker
                    style="width: 100%"
                    :disabled="formDisabled"
                    placeholder="请选择调入日期"
                    @change="handleDateImportChange"
                    v-model="model.foldTime"
                    :disabled-date="disabledDate"
                    :showTime="true"
                    format="YYYY-MM-DD HH:mm"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="调入仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="foldWarehouse">
                  <a-select
                    v-model="model.foldWarehouse"
                    :disabled="formDisabled"
                    placeholder="请选择调入仓库"
                    :showSearch="true"
                    :allowClear="true"
                    :filterOption="filterOption"
                    :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
                  >
                    <a-select-option v-for="item in foldWarehouseList" :key="item.id" :value="item.id">
                      {{ item.categoryName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="5" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="purchaseFile">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.purchaseFile"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.purchaseFile)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8" style="text-align: center">
                <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
                <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
              </a-col> -->
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpPurchaseCannibalizeFormPrint v-if="formBpm" class="print_style" id="purchaseCannibalize" :formData="model" :formDataHistory="formData"></ErpPurchaseCannibalizeFormPrint>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import { viewFile } from '@/utils/util'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import ErpPurchaseCannibalizeDetailList from './reference/ErpPurchaseCannibalizeDetailList'
import { mapGetters } from 'vuex'
import moment from 'moment'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectTeamInputCanBack from '@/views/scy/components/SelectTeamInputCanBack'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import Print from '@/utils/print/printarea.js';
import ErpPurchaseCannibalizeFormPrint from './ErpPurchaseCannibalizeFormPrint.vue'; // 打印定制
export default {
  name: 'ErpPurchaseCannibalizeForm',
  mixins: [viewFile],
  components: {
    SelectUserByDep,
    ViewFileModal,
    ErpPurchaseCannibalizeDetailList,
    SelectTeamInput,
    SelectTeamInputCanBack,
    CommonFlowList,
    ErpPurchaseCannibalizeFormPrint
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      purchaseCannibalizeDetailList: [], // 子表数据
      activeKey: ['1', '2', '3', '4', '5'],
      model: {
        purchaseBill: null
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      validatorRules: {
        // dateReturn: [
        //   {required: true, message: '请选择预计归返日期!', trigger: 'change'}
        // ],
        // payBack: [
        //   {required: true, message: '请选择偿还方式!', trigger: 'blur'}
        // ],
        purchaseUse: [
          { required: true, message: '请选择物品用途!', trigger: 'blur' }
        ],
        // foldApplicant: [
        //     { required: true, message: '请选择调入单位!', trigger: 'change' }
        // ],
        foldTeamId: [
          { required: true, message: '请选择调入团队!', trigger: 'change' }
        ],
        foldTime: [
          { required: true, message: '请选择调入日期!', trigger: 'change' }
        ],
        foldWarehouse: [
          { required: true, message: '请选择调入仓库!', trigger: 'blur' }
        ],
        // exportApplicant: [
        //     { required: true, message: '请选择调出单位!', trigger: 'change' }
        // ],
        exportTeamId: [
          { required: true, message: '请选择调出团队!', trigger: 'change' }
        ],
        exportTime: [
          { required: true, message: '请选择调出日期!', trigger: 'change' }
        ],
        exportWarehouse: [
          { required: true, message: '请选择调出仓库!', trigger: 'blur' }
        ]
      },
      url: {
        add: '/api/erp/purchase/recipients/erpPurchaseCannibalize/add',
        edit: '/api/erp/purchase/recipients/erpPurchaseCannibalize/edit',
        queryById: '/api/erp/purchase/recipients/erpPurchaseCannibalize/queryById',
        gainBillNo: '/api/erp/purchase/recipients/erpPurchaseCannibalize/gainBillNo',
        queryByDepartment: '/api/erp/purchase/storehouse/erpStorehouseBase/queryByDepartment',
        checkErpPurchaseCannibalize: '/api/erp/purchase/recipients/erpPurchaseCannibalize/checkErpPurchaseCannibalize'
      },
      foldWarehouseList: [],
      exportWarehouseList: [],
      modelExportTime: null,
      modelFoldTime: null,
      userName: '',
      warehouse: null, // 当前调出
      exportTeamId: null// 当前吊出团队
    }
  },
  watch: {
    activeKey(key) {
      this.$forceUpdate()
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    // 如果是流程中表单，则需要加载流程表单data
    this.showFlowData();
  },
  methods: {
    // 调入日期
    handleDateImportChange(mom, dateStr) {
      if (!this.model.exportTime) {
        this.model.foldTime = null
        this.$message.warning('请先选择调出日期')
        return
      }
      this.modelFoldTime = dateStr
      if (this.model.exportTime) {
        if (moment(this.model.foldTime).diff(moment(this.model.exportTime), 'minutes') < 0) {
          this.model.foldTime = this.model.exportTime
          this.$message.warning('调入日期时间不得小于调出日期时间')
        }
      }
    },
    // 调出日期
    handleDateExportChange(dateStr) {
      if (dateStr) {
        this.model.exportTime = moment(dateStr).format('YYYY-MM-DD HH:mm:ss')
        this.modelExportTime = this.model.exportTime
      } else {
        this.model.exportTime = null
        this.modelExportTime = this.model.exportTime
      }
    },
    disabledDate(current) {
      if (this.model.exportTime) {
        return current < moment(moment(this.model.exportTime).format('YYYY-MM-DD')).subtract('day')
      }
    },
    ...mapGetters(['userInfo']),
    handleChangeExportTeamId(val, num = 0) {
      if (this.exportTeamId != this.model.exportTeamId) {
        this.$refs.cannibalizeDetailList.reset()
      }
      if (val.length > 0) {
        let v = val[0].id
        if (v != this.exportTeamId) {
          this.exportTeamIdChange(v, num)
        }
        this.exportTeamId = this.model.exportTeamId
      }
    },
    exportTeamIdChange(v, num) {
      if (this.model.foldTeamId == v) {
        this.model.exportTeamId = this.exportTeamId
        this.$message.warning('调入团队不能和调出团队相同')
        this.$nextTick(() => {
          this.$set(this.model, 'exportTeamId', null)
          this.$set(this.model, 'exportWarehouse', undefined)
          this.exportWarehouseList = []
        })
        return false
      }
      // 清空子表
      this.$refs.cannibalizeDetailList.reset()
      this.warehouse = null
      const that = this
      getAction(this.url.queryByDepartment, { department: v }).then((res) => {
        if (res.success) {
          that.exportWarehouseList = []
          if (!num) {
            this.$set(this.model, 'exportWarehouse', undefined)
            this.warehouse = null
          }
          res.result.forEach((res) => {
            that.exportWarehouseList.push({ 'id': res.id, 'categoryName': res.storehouseName })
          })
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleChangeFoldTeamId(val, num = 0) {
      if (val.length > 0) {
        let v = val[0].id
        this.foldTeamIdChange(v, num)
      }
    },
    foldTeamIdChange(v, num) {
      if (this.model.exportTeamId == v) {
        this.$message.warning('调入团队不能和调出团队相同')
        this.$nextTick(() => {
          this.$set(this.model, 'foldTeamId', null)
          this.$set(this.model, 'foldWarehouse', undefined)
          this.foldWarehouseList = []
        })
        return false
      }
      const that = this
      getAction(this.url.queryByDepartment, { department: v }).then((res) => {
        if (res.success) {
          that.foldWarehouseList = []
          if (!num) {
            this.$set(this.model, 'foldWarehouse', undefined)
          }
          res.result.forEach((res) => {
            that.foldWarehouseList.push({ 'id': res.id, 'categoryName': res.storehouseName })
          })
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    getBillNo() {
      const that = this
      getAction(this.url.gainBillNo).then((res) => {
        if (res.success) {
          that.model.purchaseBill = res.result// 单据编号
          that.model.bpmBizTitle = that.userName + '-' + that.model.purchaseBill// 标题
        }
      })
    },
    add() {
      this.edit(this.modelDefault);
      this.userName = this.userInfo().empName;// 当前登录人名称
      this.model.proposer = this.userInfo().empId; // 当前登录人
      this.model.applicant = this.userInfo().deptId; // 当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      this.getBillNo() // 获取单据编号
      // this.modelExportTime = null
      // this.modelFoldTime = null
    },
    edit(record) {
      this.$refs['form'].clearValidate();
      this.model = Object.assign({}, record);
      if (this.model.id) {
        this.$refs.cannibalizeDetailList.loadData(1, this.model.id)
      } else {
        this.$refs.cannibalizeDetailList.dataSource = []
      }
      if (this.model.foldTeamId) {
        this.foldTeamIdChange(this.model.foldTeamId, 1)
      } else {
        this.foldWarehouseList = []
      }
      if (this.model.exportTeamId) {
        this.exportTeamIdChange(this.model.exportTeamId, 1)
      } else {
        this.exportWarehouseList = []
      }
      if (record.foldTime) {
        this.modelFoldTime = record.foldTime
        this.model.foldTime = moment(record.foldTime, 'YYYY-MM-DD HH:mm')
      } else {
        this.modelFoldTime = null
      }
      if (record.exportTime) {
        this.modelExportTime = record.exportTime
        this.model.exportTime = moment(record.exportTime, 'YYYY-MM-DD HH:mm')
      } else {
        this.modelExportTime = null
      }
      // 当前的仓库
      this.warehouse = this.model.exportWarehouse
      // 当前团队
      this.exportTeamId = this.model.exportTeamId
      this.visible = true;
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId };
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result);
          }
        });
      }
    },

    submitForm(type) {
      const that = this;
      if (type == 'draft') {
        // 代表保存草稿不做校验
        this.submit(type)
      } else if (type == 'submit') {
        let details = this.$refs.cannibalizeDetailList.submitForm()
        if (!details.length > 0) {
          this.$message.warning('请添加物资明细信息！');
          this.$emit('unButtonDisable');
          return
        }
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.submit(type)
          } else {
            that.$emit('unButtonDisable')
          }
        })
      } else {
        console.log('传参数，保存：draft，提交：submit')
      }
    },
    submit (type) {
      const that = this;
      let details = this.$refs.cannibalizeDetailList.submitForm() || []
      that.confirmLoading = true;
      let httpurl = '';
      let method = '';
      if (!this.model.id) {
        httpurl += this.url.add;
        method = 'post';
      } else {
        httpurl += this.url.edit;
        method = 'put';
      }
      this.model.detailList = details
      this.model.foldTime = this.modelFoldTime
      this.model.exportTime = this.modelExportTime
      httpAction(httpurl, this.model, method).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          if (method == 'post') {
            that.model.id = res.result;
          }
          that.$emit('ok', type, that.model);
        } else {
          that.$message.warning(res.message);
          that.$emit('unButtonDisable');
        }
      }).catch((error) => {
        that.$emit('unButtonDisable', error);
      }).finally(() => {
        that.confirmLoading = false;
      })
    },
    getList (arr) {
      this.purchaseCannibalizeDetailList = arr
    },
    // 检查库存
    checkErpPurchaseCannibalize() {
      let details = this.$refs.cannibalizeDetailList.submitForm()
      console.log('details：', details)
      if (!!details && details.length != 0) {
        this.model.detailList = details
        this.model.foldTime = this.modelFoldTime
        this.model.exportTime = this.modelExportTime
        httpAction(this.url.checkErpPurchaseCannibalize, this.model, 'post').then(res => {
          if (res.success && !!res.result && res.result.isOk) {
            this.submitForm('submit')
          } else if (!res.result.isOk) {
            this.$message.warning('（调出团队） ' + this.model.exportWarehouse_dictText + ' 仓库 ' + res.result.material_dictText + ' ' + res.result.message)
            this.$emit('unButtonDisable');
          }
        }).catch(err => {
          this.$message.warning(err.message);
            this.$emit('unButtonDisable');
        })
      } else {
        this.$message.warning('请添加物资明细信息！');
          this.$emit('unButtonDisable');
      }
    },
    // 修改仓库时
    handleExportWarehouseChange(value, option) {
      let that = this;
      if (this.warehouse) {
        this.$confirm({
          title: '是否确认',
          content: '是否确认切换仓库，此操作将会清空明细表中已填写的所有信息？',
          okText: '确定',
          cancelText: '取消',
          onOk() {
            if (!that.disabled && !!that.model.exportWarehouse) {
              // 清空子表
              that.$refs.cannibalizeDetailList.reset()
              // 修改当前仓库
              that.warehouse = value
            }
          },
          onCancel() {
            // 恢复切换前
            that.model.exportWarehouse = that.warehouse
          }
        });
      } else {
        this.warehouse = value
      }

      console.log(this.exportWarehouseList)
      this.exportWarehouseList.forEach(ex => {
        if (ex.id == value) {
          this.$set(this.model, 'exportWarehouse_dictText', ex.categoryName)
        }
      })
    },

    // 点击打印
    onPrint () {
        let print = new Print({
          el: '#purchaseCannibalize',
          popTitle: '物资调拨申请详情 · 禾美环保',
          endCallback() {

          }
        })
      }
    // backUserInfo(data) {
    //   this.model.applicant = data[0].orgDepart;//申请人单位
    // }
  }
}
</script>
